package com.beta.mq.redis.aop;


import com.alibaba.fastjson.JSON;
import com.beta.mq.redis.constant.CommonConstant;
import com.beta.mq.redis.constant.TopicConstant;
import com.beta.mq.redis.enums.PageEnum;
import com.beta.mq.redis.model.Message;
import com.beta.mq.redis.model.StatisticsData;
import com.beta.mq.redis.producer.Producer;
import com.beta.mq.redis.producer.annotation.ShareStatistics;
import com.beta.platform.rest.auth.SignetSecurity;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect
public class ShareStatisticsAspect {

    @Autowired
    private Producer producer;

    @After("@annotation(com.beta.mq.redis.producer.annotation.ShareStatistics)")
    public void afterMethod(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取请求入参的Map
        String shareId = request.getHeader(CommonConstant.SHARE);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ShareStatistics annotation = method.getAnnotation(ShareStatistics.class);
        String pageCode = annotation.pageCode();

        try {
            StatisticsData data = new StatisticsData();
            data.setPageCode(pageCode);
            data.setPageName(PageEnum.getPageNameByCode(pageCode));
            data.setCurrentTime(LocalDateTime.now());
            data.setCustId(getCustId(request));
            //客户打开浏览分享页面
            if (StringUtils.isNotEmpty(shareId)) {
                data.setCustManagerId(SignetSecurity.getSignet().getUserId());
                data.setType(CommonConstant.READ);
                producer.sendMessage(TopicConstant.SHARE_STATISTICS, new Message(data));
            }
            log.info("share statistics data : {}", JSON.toJSONString(data));
        } catch (Exception e) {
            log.error("统计分享页面：{}异常, 异常原因：{}", pageCode, e.getMessage(), e);
        }

    }

    private String getCustId(HttpServletRequest request) throws IOException {
        String custId = request.getParameter(CommonConstant.CUST);
        if (StringUtils.isEmpty(custId)) {
            StringBuilder bodyContent = new StringBuilder();
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                bodyContent.append(line);
            }
            JsonObject jsonObject = JsonParser.parseString(bodyContent.toString()).getAsJsonObject();
            custId = jsonObject.get(CommonConstant.CUST).getAsString();
        }
        return custId;
    }

}
